package com.apes.scm.sal.saleReturn;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.service.UomService;
import com.apes.scm.sal.saleOrder.SaleOrderItem;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Map;

/**
 * 功能：分销退货
 *
 * @author xul
 * @create 2018-01-25 19:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SaleReturnItem.CONST_TABLE_NAME)
public class SaleReturnItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "sale_return_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "分销退货明细")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier;

    @ManyToOne(optional = false)
    @JoinColumn(name = "sale_return_id", referencedColumnName = "id", nullable = false)
    @Comment("订单")
    private SaleReturn saleReturn;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "sale_order_item_id", referencedColumnName = "id")
    @Comment("原订单行号")
    private SaleOrderItem saleOrderItem;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id", nullable = false)
    @Comment("商品")
    private Product product;

    @Column(name = "remark", length = 120)
    @Comment("备注")
    private String remark;

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("小计（未含税金额）")
    private double priceSubtotal = 0;

    @Column(name = "price_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double priceTax = 0;

    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double priceTotal = 0;

    @Column(name = "discount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("折扣（返利）金额")
    private double discount = 0;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("单价")
    private double priceUnit = 0;

    @Column(name = "product_uom_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("数量")
    private double productUomQty = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id", nullable = false)
    @Comment("计量单位")
    private ProductUom uom;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id", nullable = false)
    @Comment("税率")
    private Tax tax;

    @Column(name = "qty_invoiced", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("开票数量")
    private double qtyInvoiced = 0;

    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("收货数量")
    private double qtyDeliver = 0;



    @Column(name = "qty_delivering", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("提单冲红数量")
    private double qtyDelivering = 0;

    @Column(name = "qty_delivered", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("退货冲红数量")
    private double qtyDelivered = 0;

    public void computeAmt() {
        Map result = this.computeTax().computeAll(this.getCompany(), priceUnit, productUomQty);
        priceTax = ((Double) result.get("taxAmt")).doubleValue();
        priceSubtotal = ((Double) result.get("totalExcluded")).doubleValue();
        priceTotal = ((Double) result.get("totalIncluded")).doubleValue();
    }

    /*
     * 功能：计算无税库存单价
     */
    public double computeExcludedPriceUnit() {
        double price = this.priceUnit;
        if (this.getTax() != null) {
            price = (double) this.getTax().computeAll(this.getSaleReturn().getCompany(), price, 1.0).get("totalExcluded");
        }
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /*
     * 功能：计算含税库存单价
     */
    public double computePriceUnit() {
        double price = this.priceUnit;
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /*
     * 功能：计算基本单位库存量
     */
    public double computeQtyUnit(double uomQty) {
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            return this.getUom().computeQty(uomQty, baseUom, true);
        }
        return uomQty;
    }

    private ProductUom getProductUom() {
        UomService uomService = SpringManager.getBean(UomService.class);
        return uomService.getUom(this.getCompany(), this.getProduct());
    }


    private Tax computeTax(){
        TaxService taxService = SpringManager.getBean(TaxService.class);
        tax = taxService.getSaleTax(saleReturn.getCompany(), product);
        return tax;
    }
    /**
     * 收货
     */
    public void delivery(double qtyDone) {
        this.qtyDeliver += qtyDone;
        if (qtyDeliver > qtyDelivered) {
            throw new RuntimeException("收货数量不允许大于退货冲红数量！，当前可退数量为：" + (qtyDelivered - qtyDeliver) + "当前收货数量为：" + qtyDone);
        }
    }

    @Transient
    private Double qtyDeliveringLimit;  // 获取实时可提单冲红数量
    public Double getQtyDeliveringLimit() {
        if (!saleReturn.getState().equals("sent")){
            return null;
        }
        if(saleOrderItem == null){
            return null;
        }
        // 可提单冲红数量 = 销售数量 - 交货数量 - 取消数量 + 退货中数量（提单冲红） + 当前单据的提单冲红数量

        if (LogicalUtil.in(product.getType(), "aut")) {
            double number = saleOrderItem.getUom().computeQty(saleOrderItem.getProductUomQty() - saleOrderItem.getQtyDeliver()
                    - saleOrderItem.getQtyCancle() - saleOrderItem.getQtyDelivering() + qtyDelivering, uom, true);
            return number > 0 ? number:0;
        } else {
            return 0.0;
        }

    }

    @Transient
    private Double qtyDeliveredLimit;  // 获取实时可退货冲红数量
    public Double getQtyDeliveredLimit() {
        if (!saleReturn.getState().equals("sent")){
            return null;
        }
        if(saleOrderItem == null){
            return null;
        }

        // 可退货冲红数量 = 交货数量 - (退货数量 - 取消数量) -退货中数量（退货冲红）+ 当前单据的退货冲红数量
        if (LogicalUtil.in(product.getType(), "aut")) {
            return 0.0;
        } else {
            double number = saleOrderItem.getUom().computeQty(saleOrderItem.getQtyDeliver() - (saleOrderItem.getQtyReturned()
                    - saleOrderItem.getQtyCancle()) - saleOrderItem.getQtyDelivered() + qtyDelivered, uom, true) ;
            return number > 0 ? number:0;
        }
    }

    @Transient
    private Double negativeProductUomQty;  // 获取数量的负数用于生成账单
    public Double getNegativeProductUomQty() {
        return -1.00 * productUomQty;
    }

    @Transient
    private Double negativeDiscount;  // 获取折扣的负数用于生成账单
    public Double getNegativeDiscount() {
        return -1.00 * discount;
    }

    /***
     * 功能：合计退货数量
     * @param
     */
    public void sumProductUomQty() {
        this.productUomQty = this.qtyDelivering + this.qtyDelivered;
    }


    /***
     * 功能：验证提单退货数据的合法性
     * @param qtyDelivering
     */
    public void setQtyDelivering(double qtyDelivering) {
        if(this.qtyDeliveringLimit != null &&  this.qtyDeliveringLimit < qtyDelivering){
            throw new RuntimeException("提单退货数量不能大于实际可提单退货数量，当前可退回数量为：" + qtyDeliveringLimit);
        }
        this.qtyDelivering = qtyDelivering;
    }

    /***
     * 功能：验证退货冲红数量的合法性
     * @param qtyDelivered
     */
    public void setQtyDelivered(double qtyDelivered) {
        if(this.qtyDeliveredLimit != null &&  this.qtyDeliveredLimit < qtyDelivered){
            throw new RuntimeException("退货冲红数量不能大于实际可退货冲红数量，当前可退回数量为：" + qtyDeliveredLimit);
        }
        this.qtyDelivered = qtyDelivered;
    }


//    /***
//     * 功能：验证退货数量的合法性
//     * @param productUomQty
//     */
//    public void setProductUomQty(double productUomQty) {
//        if(this.productUomQtyLimit != null &&  this.productUomQtyLimit < productUomQty){
//            throw new RuntimeException("退货数量不能大于实际可退货数量，当前可退回数量为：" + productUomQtyLimit);
//        }
//        this.productUomQty = productUomQty;
//    }
}
